<template>
  <view :class="['statistics-container', `theme-${currentTheme}`]">
    <!-- 总体统计 -->
    <view class="overview-section">
      <view class="stat-card">
        <text class="stat-label">总收礼</text>
        <text class="stat-value receive">¥{{ formatAmount(totalReceive) }}</text>
      </view>
      <view class="stat-card">
        <text class="stat-label">总送礼</text>
        <text class="stat-value give">¥{{ formatAmount(totalGive) }}</text>
      </view>
      <view class="stat-card">
        <text class="stat-label">净往来</text>
        <text class="stat-value" :class="{ receive: netAmount >= 0, give: netAmount < 0 }">
          ¥{{ formatAmount(Math.abs(netAmount)) }}
        </text>
      </view>
    </view>

    <!-- 趋势图表 -->
    <view class="chart-section">
      <view class="section-header">
        <text class="section-title">收支趋势</text>
        <view class="chart-tab">
          <text 
            class="tab-item" 
            :class="{ active: trendChartType === 'line' }" 
            @click="handleTrendChartTypeChange('line')"
          >折线图</text>
          <text 
            class="tab-item" 
            :class="{ active: trendChartType === 'bar' }" 
            @click="handleTrendChartTypeChange('bar')"
          >柱状图</text>
        </view>
      </view>
      
      <view class="chart-container trend-chart">
        <canvas canvas-id="trendChart" class="chart-canvas"></canvas>
      </view>
    </view>

    <!-- 分类统计 -->
    <view class="chart-section">
      <view class="section-header">
        <text class="section-title">礼簿统计</text>
      </view>
      
      <!-- 表格视图 -->
      <view class="category-list">
        <view v-for="category in categoryStats" :key="category.id" class="category-item">
          <view class="category-info">
            <text class="category-name">{{ category.name }}</text>
            <text class="category-count">{{ category.count }}笔</text>
          </view>
          <view class="category-amount">
            <text class="amount-label">收礼</text>
            <text class="amount-value receive">¥{{ formatAmount(Number(category.receive)) }}</text>
            <text class="amount-label">送礼</text>
            <text class="amount-value give">¥{{ formatAmount(Number(category.give)) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部占位，确保所有内容都能显示 -->
    <view class="bottom-space"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useGiftBookStore } from '@/store/modules/giftbook';
import { useThemeStore } from '@/store/modules/theme';
import useThemeMixin from '@/mixins/themeMixin';
import { GiftBook } from '@/types/giftbook';

// 定义分类和图表数据的接口
interface CategoryStat {
  id: string | number;
  name: string;
  count: number;
  receive: string;
  give: string;
}

interface ChartDataPoint {
  year: number;
  receive: number;
  give: number;
}

const giftBookStore = useGiftBookStore();
const themeStore = useThemeStore();

const currentTheme = computed(() => themeStore.currentTheme);

// 使用主题mixin
useThemeMixin();

// 图表类型
const trendChartType = ref('bar');

// 格式化金额，大数字使用简写，整数不显示小数部分
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0';
  
  // 对大金额进行简化处理
  if (amount >= 100000000) { // 亿
    const value = amount / 100000000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '亿';
  } else if (amount >= 10000) { // 万
    const value = amount / 10000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '万';
  }
  
  // 整数金额不显示小数点后的零
  return Number.isInteger(amount) ? amount.toString() : amount.toFixed(2);
};

// 计算总体统计数据
const totalReceive = computed(() => {
  let total = 0;
  giftBookStore.getAllGiftBooks.forEach((book: GiftBook) => {
    total += book.totalReceived || 0;
  });
  return total;
});

const totalGive = computed(() => {
  let total = 0;
  giftBookStore.getAllGiftBooks.forEach((book: GiftBook) => {
    total += book.totalGiven || 0;
  });
  return total;
});

const netAmount = computed(() => {
  return Number(totalReceive.value) - Number(totalGive.value);
});

// 获取礼簿类别统计数据
const categoryStats = computed<CategoryStat[]>(() => {
  const typeMap = new Map<string, CategoryStat>();
  
  giftBookStore.getAllGiftBooks.forEach((book: GiftBook) => {
    const bookType = book.type;
    const typeKey = bookType.toString();
    
    if (!typeMap.has(typeKey)) {
      typeMap.set(typeKey, {
        id: typeKey,
        name: getTypeName(bookType),
        count: 0,
        receive: '0',
        give: '0'
      });
    }
    
    const stat = typeMap.get(typeKey)!;
    stat.count += book.records.length;
    stat.receive = (Number(stat.receive) + (book.totalReceived || 0)).toFixed(2);
    stat.give = (Number(stat.give) + (book.totalGiven || 0)).toFixed(2);
  });
  
  return Array.from(typeMap.values());
});

// 获取礼簿类型名称
function getTypeName(type: string): string {
  switch (type) {
    case 'wedding': return '婚礼';
    case 'funeral': return '白事';
    case 'birthday': return '生日';
    case 'graduation': return '升学';
    case 'business': return '商务';
    case 'housewarming': return '乔迁';
    case 'fullmoon': return '满月';
    default: return '其他';
  }
}

// 图表类型切换处理
const handleTrendChartTypeChange = (type: string) => {
  trendChartType.value = type;
  drawTrendChart();
};

// 获取年度统计数据
const getYearlyData = (): ChartDataPoint[] => {
  const yearMap = new Map<number, ChartDataPoint>();
  
  giftBookStore.getAllGiftBooks.forEach((book: GiftBook) => {
    const bookDate = new Date(book.date);
    const year = bookDate.getFullYear();
    
    if (!yearMap.has(year)) {
      yearMap.set(year, {
        year,
        receive: 0,
        give: 0
      });
    }
    
    const yearData = yearMap.get(year)!;
    yearData.receive += book.totalReceived || 0;
    yearData.give += book.totalGiven || 0;
  });
  
  return Array.from(yearMap.values()).sort((a, b) => a.year - b.year);
};

// 四舍五入到合适的刻度
const roundToNiceNumber = (num: number): number => {
  const exponent = Math.floor(Math.log10(num));
  const power10 = Math.pow(10, exponent);
  const normalizedNum = num / power10;
  
  let niceNum;
  if (normalizedNum < 1.5) niceNum = 1;
  else if (normalizedNum < 3) niceNum = 2;
  else if (normalizedNum < 7) niceNum = 5;
  else niceNum = 10;
  
  return niceNum * power10;
};

// 绘制趋势图表
const drawTrendChart = () => {
  const ctx = uni.createCanvasContext('trendChart');
  const width = 350; // 增加宽度
  const height = 250; // 增加高度
  const padding = 45; // 增加内边距
  
  // 获取年度数据
  const yearlyData = getYearlyData();
  
  // 如果没有数据
  if (yearlyData.length === 0) {
    ctx.setFillStyle('#999');
    ctx.setFontSize(14);
    ctx.setTextAlign('center');
    ctx.fillText('暂无数据', width / 2, height / 2);
    ctx.draw();
    return;
  }
  
  // 计算最大值
  const maxAmount = Math.max(
    ...yearlyData.map(data => Math.max(data.receive, data.give)),
    1
  );
  
  const yAxisMax = roundToNiceNumber(maxAmount * 1.1);
  
  // 清空画布
  ctx.clearRect(0, 0, width, height);
  
  // 绘制网格和坐标轴
  ctx.beginPath();
  ctx.setLineWidth(1);
  ctx.setStrokeStyle('#eee');
  
  // 横向网格线和Y轴
  const yGridCount = 5;
  for (let i = 0; i <= yGridCount; i++) {
    const y = padding + (height - padding * 2) * (i / yGridCount);
    
    // 绘制横向网格线
    ctx.moveTo(padding, y);
    ctx.lineTo(width - padding, y);
    
    // 绘制Y轴刻度值
    const scaleValue = formatAmount((yAxisMax * (yGridCount - i) / yGridCount));
    ctx.setFillStyle('#666');
    ctx.setFontSize(10); // 稍微增大刻度文字
    ctx.setTextAlign('right');
    ctx.fillText(scaleValue, padding - 5, y + 3);
  }
  
  ctx.stroke();
  
  // 绘制坐标轴
  ctx.beginPath();
  ctx.setLineWidth(1);
  ctx.setStrokeStyle('#ccc');
  ctx.moveTo(padding, padding);
  ctx.lineTo(padding, height - padding);
  ctx.lineTo(width - padding, height - padding);
  ctx.stroke();
  
  if (trendChartType.value === 'line') {
    // 折线图
    const xStep = (width - padding * 2) / (yearlyData.length - 1 || 1);
    const yScale = (height - padding * 2) / yAxisMax;
  
  // 收礼线
  ctx.beginPath();
  ctx.setLineWidth(2);
  ctx.setStrokeStyle('#67c23a');
    
    yearlyData.forEach((data, i) => {
    const x = padding + i * xStep;
      const y = height - padding - data.receive * yScale;
      
      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
      
      // 在数据点上绘制圆点
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI * 2); // 增大圆点
      ctx.setFillStyle('#67c23a');
      ctx.fill();
      
      // 只在数据点上方显示显著的数据值
      if (data.receive > maxAmount * 0.05) {
        ctx.setFillStyle('#333');
        ctx.setFontSize(12); // 增大数值字体
        ctx.setTextAlign('center');
        ctx.fillText(formatAmount(data.receive), x, y - 10);
      }
      
      // 重新开始路径
      ctx.beginPath();
      ctx.setStrokeStyle('#67c23a');
      ctx.setLineWidth(2);
    if (i === 0) {
      ctx.moveTo(x, y);
    } else {
      ctx.lineTo(x, y);
    }
  });
    
  ctx.stroke();
  
  // 送礼线
  ctx.beginPath();
  ctx.setLineWidth(2);
  ctx.setStrokeStyle('#f56c6c');
    
    yearlyData.forEach((data, i) => {
    const x = padding + i * xStep;
      const y = height - padding - data.give * yScale;
      
      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
      
      // 在数据点上绘制圆点
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, Math.PI * 2); // 增大圆点
      ctx.setFillStyle('#f56c6c');
      ctx.fill();
      
      // 只在数据点上方显示显著的数据值
      if (data.give > maxAmount * 0.05) {
        ctx.setFillStyle('#333');
        ctx.setFontSize(12); // 增大数值字体
        ctx.setTextAlign('center');
        ctx.fillText(formatAmount(data.give), x, y - 10);
      }
      
      // 重新开始路径
      ctx.beginPath();
      ctx.setStrokeStyle('#f56c6c');
      ctx.setLineWidth(2);
    if (i === 0) {
      ctx.moveTo(x, y);
    } else {
      ctx.lineTo(x, y);
    }
  });
    
  ctx.stroke();
  } else {
    // 柱状图
    const barWidth = 14; // 增加柱宽
    const barGap = 4; // 增加间距
    const groupWidth = (width - padding * 2) / yearlyData.length;
    const yScale = (height - padding * 2) / yAxisMax;
    
    // 绘制柱状
    yearlyData.forEach((data, i) => {
      const x = padding + i * groupWidth + groupWidth / 2;
      
      // 收礼柱
      const receiveHeight = data.receive * yScale;
      if (receiveHeight > 0) {
        ctx.beginPath();
        ctx.setFillStyle('#67c23a');
        ctx.rect(x - barWidth - barGap/2, height - padding - receiveHeight, barWidth, receiveHeight);
        ctx.fill();
        
        // 显示数值，始终在柱状图顶部
        ctx.setFillStyle('#333');
        ctx.setFontSize(11);
        ctx.setTextAlign('center');
        ctx.fillText(formatAmount(data.receive), x - barWidth - barGap/2 + barWidth/2, height - padding - receiveHeight - 6);
      }
      
      // 送礼柱
      const giveHeight = data.give * yScale;
      if (giveHeight > 0) {
        ctx.beginPath();
        ctx.setFillStyle('#f56c6c');
        ctx.rect(x + barGap/2, height - padding - giveHeight, barWidth, giveHeight);
        ctx.fill();
        
        // 显示数值，始终在柱状图顶部
        ctx.setFillStyle('#333');
        ctx.setFontSize(11);
        ctx.setTextAlign('center');
        ctx.fillText(formatAmount(data.give), x + barGap/2 + barWidth/2, height - padding - giveHeight - 6);
      }
      
      // 绘制X轴年份标签
      ctx.setFillStyle('#333');
      ctx.setFontSize(12); // 增大年份标签
      ctx.setTextAlign('center');
      ctx.fillText(data.year.toString(), x, height - padding + 16);
    });
  }
  
  // 绘制图例
  const legendX = width - 100; // 调整图例位置
  const legendY = padding + 10;
  
  // 收礼图例
  ctx.beginPath();
  ctx.setFillStyle('#67c23a');
  ctx.rect(legendX, legendY, 18, 10); // 增大图例标记
  ctx.fill();
  ctx.setFillStyle('#333');
  ctx.setFontSize(12); // 增大图例文字
  ctx.setTextAlign('left');
  ctx.fillText('收礼', legendX + 24, legendY + 9);
  
  // 送礼图例
  ctx.beginPath();
  ctx.setFillStyle('#f56c6c');
  ctx.rect(legendX, legendY + 20, 18, 10); // 增大图例标记
  ctx.fill();
  ctx.setFillStyle('#333');
  ctx.fillText('送礼', legendX + 24, legendY + 29);
  
  ctx.draw();
};

// 渲染图表的函数
const renderCharts = () => {
  drawTrendChart();
};

// 监听礼簿数据变化，自动刷新图表
watch(() => giftBookStore.getAllGiftBooks, renderCharts, { deep: true });

// 下拉刷新处理
const onPullDownRefresh = async () => {
  try {
    await giftBookStore.loadFromStorage();
    renderCharts();
    uni.showToast({
      title: '刷新成功',
      icon: 'success'
    });
  } catch (error) {
    uni.showToast({
      title: '刷新失败',
      icon: 'error'
    });
  } finally {
    uni.stopPullDownRefresh();
  }
};

// 生命周期
onMounted(async () => {
  // 加载礼簿数据
  await giftBookStore.loadFromStorage();
  
  // 延迟绘制图表，确保canvas已经渲染
  setTimeout(renderCharts, 100);
});
</script>

<style lang="scss">
.statistics-container {
  padding: 20rpx;
  background-color: var(--background-color);
  min-height: 100vh;

  &.theme-funeral {
    --primary-light: #F5F5F5;
  }
}

.overview-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  .stat-card {
    flex: 1;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    text-align: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .stat-label {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .stat-value {
      display: block;
      font-size: 38rpx;
      font-weight: bold;
      
      &.receive {
        color: #67c23a;
      }
      
      &.give {
        color: #f56c6c;
      }
    }
  }
}

.chart-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    }
    
    .chart-tab {
      display: flex;
      
      .tab-item {
        padding: 8rpx 24rpx;
        font-size: 24rpx;
        color: #666;
        border-radius: 8rpx;
        margin-left: 10rpx;
        transition: all 0.3s ease;
        
        &.active {
          background-color: var(--primary-color);
          color: #fff;
        }
      }
    }
  }
  
  .chart-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    
    &.trend-chart {
      height: 500rpx;
    }
    
    &.category-chart {
      height: 600rpx;
    }
    
    .chart-canvas {
      width: 100%;
      height: 100%;
    }
  }
  
  .category-list {
    .category-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #eee;
      
      &:last-child {
        border-bottom: none;
      }
      
      .category-info {
        .category-name {
          font-size: 28rpx;
          color: #333;
          margin-right: 20rpx;
        }
        
        .category-count {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .category-amount {
        .amount-label {
          font-size: 24rpx;
          color: #999;
          margin-right: 10rpx;
        }
        
        .amount-value {
          font-size: 28rpx;
          margin-right: 20rpx;
          
          &.receive {
            color: #67c23a;
          }
          
          &.give {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

.bottom-space {
  height: 120rpx;
}
</style> 